const express = require("express")
const { v4 } = require("uuid")
const { query } = require("../db/db")
const moment = require("moment")
const router = express.Router()

router.get("/list", (req, res) => {
  let sql = `select * from blog_knowledge order by update_time desc, create_time desc`
  let value = []
  query(sql, value)
    .then((data) => {
      console.log(data.data)
      res.json(data)
    })
    .catch((err) => {
      res.json(err)
    })
})

router.post("/create", (req, res) => {
  const { type, title, html } = req.body
  const sql = `insert into blog_knowledge (id, type,title,html,create_time) values (?,?,?,?,?)`
  const value = [
    v4().toString().replace(/-/g, ""),
    type,
    title,
    html,
    new Date()
  ]
  query(sql, value)
    .then((data) => {
      res.json(data)
    })
    .catch((err) => {
      res.json(err)
    })
})

router.post("/search", (req, res) => {
  const { type,title } = req.body
  let sql = ''
  if (type) {
    sql = `select * from blog_knowledge where type='${type}' and title LIKE '%${title}%' order by update_time desc, create_time desc`
  } else {
    sql = `select * from blog_knowledge where title LIKE '%${title}%' order by update_time desc, create_time desc`
  }
  const value = []
  query(sql, value)
    .then((data) => {
      res.json(data)
    })
    .catch((err) => {
      res.json(err)
    })
})

router.post("/update", (req, res) => {
  const { id, type, title, html } = req.body
  const sql = `update blog_knowledge set ? where id='${id}'`
  const value = {
    type,
    title,
    html,
    update_time: new Date()
  }
  query(sql, value)
    .then((data) => {
      res.json(data)
    })
    .catch((err) => {
      res.json(err)
    })
})

router.post("/delete", (req, res) => {
  const { id } = req.body
  const sql = `delete from blog_knowledge where id='${id}'`
  const value = []
  query(sql, value)
    .then((data) => {
      res.json(data)
    })
    .catch((err) => {
      res.json(err)
    })
})

module.exports = router
